package cn.zxy.advice;

import cn.hutool.json.JSONUtil;
import cn.zxy.exception.BizException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import cn.zxy.dto.ResponseDTO;

@RestControllerAdvice

public class MyResponseAdvice implements ResponseBodyAdvice<Object> {

    //为什么实现的是ResponseBodyAdvice？
    //因为不确定接口<Object> 会返回什么类型，可能是List,或者是Int,... 所以用Body
    //只需要在beforeBodyWrite中封装就可以，就是开始去响应的时候做这些事情
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

//    统一异常处理
    @ExceptionHandler
    public Object processException(Exception ex){

        ex.printStackTrace();
        if (ex instanceof BizException){
            BizException bizException = (BizException) ex;
            return ResponseDTO.error(bizException.getCode(),ex.getMessage());
        }
        return ResponseDTO.error(1,ex.getMessage());
    }
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//        body 是controller里面目标方法执行的

        if (body instanceof ResponseDTO){
            return body;
        }
        ResponseDTO success = ResponseDTO.success(body);

        if (selectedConverterType == StringHttpMessageConverter.class){

            return JSONUtil.toJsonStr(success);
//            帮忙去处理string类型
        }
        return success;
    }
}
